package com.godyao.mall.goods.mq.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.godyao.mall.goods.es.model.GoodsEs;
import com.godyao.mall.goods.es.repository.GoodsEsRepository;
import com.godyao.mall.goods.mq.config.RabbitMqConfig;
import com.godyao.mall.goods.mq.model.GoodsMq;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author godyao
 * @date 2022/4/5
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GoodsRabbitListener {
    private final GoodsEsRepository goodsEsRepository;

    @SneakyThrows
    @RabbitListener(queues = {RabbitMqConfig.QUEUE_NAME})
    public void consumeGoodsQueue(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        final String data = new String(message.getBody());
        log.info("接收到一条消息，内容为：{}，唯一ID为：{}", data, deliveryTag);
        final GoodsMq goodsMq = new ObjectMapper().readValue(data, GoodsMq.class);
        final GoodsEs goodsEs = new GoodsEs();
        BeanUtils.copyProperties(goodsMq, goodsEs);
        goodsEs.setGoodsId(goodsMq.getId());
        doHandleMq(goodsEs, goodsMq.getFlag());
        // 手动确认消息
        //multiple：为了减少网络流量，手动确认可以被批处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 处理 操作类型
     * @param goodsEs
     * @param flag
     */
    private void doHandleMq(GoodsEs goodsEs, Integer flag) {
        if (Integer.valueOf(3).equals(flag)) {
            // 删除操作
            goodsEsRepository.deleteByGoodsId(goodsEs.getGoodsId());
        } else {
            goodsEsRepository.save(goodsEs);
        }
    }
}
